import React from 'react'
import {
    Button,
    message,
    Modal
} from 'antd'

import Table from 'components/table'
import {
    FormModal
} from 'components/modalForm'
import 'whatwg-fetch'
import ModelTreeSelect from "components/treeSelect"
import './index.less'

import axios from "axios";

require('es6-promise').polyfill();
axios.interceptors.request.use(function (config) {    // 这里的config包含每次请求的内容
    var type = sessionStorage.getItem("user_token");
   config.headers.user_token = type;

    return config;
}, function (err) {
    return Promise.reject(err);
});



const confirm = Modal.confirm
let arr=[{
    value: 2,
    mean: '上海',
},
    {
        value: 1,
        mean: '北京',
    }]
export default class Music extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            id:"",
            tData: [],
            item: {},
            menuDate:[],
            defaultArr:[],
            loading: true,
            modalShow: false,
            modalShowEdit: false,
            modalShowSet:false,
            total:0,
            current:1,
            pageSize:10
        }
        this.add = this.add.bind(this)
        this.onOk = this.onOk.bind(this)
        this.onCancel = this.onCancel.bind(this)
        this.onOkEdit = this.onOkEdit.bind(this)
        this.onCancelEdit = this.onCancelEdit.bind(this)
        this.onOkSet = this.onOkSet.bind(this)
        this.onCancelSet= this.onCancelSet.bind(this)
        this.changePage = this.changePage.bind(this)
    }

    // 获取表格数据
    fetchTableData = (n) => {
        axios.get(`/auth/roles?pageNum=${n}&pageSize=10`).then((res)=>{

            const roleArray =[];
            let roleList =  res.data.list;
            for (let i = 0; i < roleList.length; i++) {
                roleArray.push({
                    name: roleList[i].name,
                    //url:roleList[i].url,
                    description:roleList[i].description,
                    id:roleList[i].id
                })
            }
            this.setState({
                tData: roleArray,
                total:res.data.total,
                loading: false,
                current:n
            });

        })

    }

    componentDidMount() {
        this.fetchTableData(1) // 默认
    }

    tableHeader = () => {
        return [{
            dataIndex: 'name',
            title: '角色名',
            width: 200,
            // render: (text, record) => {
            // }
        },  {
                dataIndex: 'description',
                title: '描述',
                width: 200,
            }
           ]
    }
    changePage(n){

        this.fetchTableData(n);
    }
    add() {
        this.setState({
            modalShow: true
        })
    }

    onOk(param) {

        axios.post("/auth/roles",{
            name:param.name,
            description:param.description,

        }).then( (res)=>{
            if(res.status === 200){
                message.success('添加成功');
                this.onCancel();
                this.fetchTableData(1);
            }
        })

    }

    onOkSet(){
        let arrId = this.getId();
        console.log(arrId)
    }
    onCancel() {
        this.setState({
            modalShow: false
        })
    }
    onOkEdit(param) {
        this.setState({
            modalShowEdit: false
        });
       axios.put("/auth/roles/"+param.id,{
            name:param.name,
           description:param.description
        }).then(()=>{
           this.fetchTableData(1);
           message.success('编辑成功');
       })

    }
    onCancelSet(){
        this.setState({
            modalShowSet: false
        })
    }
    getId=(parms)=>{
        console.log(parms)
        axios.put(`/auth/roles/${this.state.id}/menus`,{
            "menuIds":parms
        }).then(()=>{
        })
    }
    onCancelEdit() {
        this.setState({
            modalShowEdit: false
        })
    }
    tableAction = (actionKey, item) => {

        if (actionKey === 'edit') {
            this.setState({
                item: item,
                modalShowEdit: true
            })
        } else if (actionKey === 'delete') {
            confirm({
                title: '提示',
                content: '确定删除吗',
                onOk: () => {
                    axios.delete(`/auth/roles/${item.id}`).then(
                        ()=>{
                            this.fetchTableData(1)
                            message.success('删除成功');

                        }
                    )

                },
                onCancel() {}
            })
        }else if (actionKey==='set'){
            axios.get(`/auth/roles/${item.id}/menus`).then((res)=>{

                var arr = [],
                    arrTwo=[];
                for (var i = 0; i <  res.data.length; i ++ ){
                    var father = {};
                    father.id = res.data[i].id;
                    father.name = res.data[i].name;
                    father.assigned=res.data[i].assigned;
                    father.url = res.data[i].resource;
                    if(res.data[i].children.length>0){
                        var children = [];
                        for (let j = 0;j<res.data[i].children.length;j++){
                            var obj  = {};
                            obj.id = res.data[i].children[j].id;
                            obj.name = res.data[i].children[j].name;
                            obj.url = res.data[i].children[j].resource;
                            obj.assigned=res.data[i].children[j].assigned;
                            children.push(obj);
                        }
                        father.children = children;
                    }
                    arr.push(father);
                }
                arr.map((el)=>{
                    if(el.children&&el.children.length>0){
                        for(let i = 0;i<el.children.length;i++){
                            if(el.children[i].assigned){
                                arrTwo.push(el.children[i].id)
                            }
                        }
                    }
                })

                this.setState({
                    defaultArr:arrTwo,
                    menuDate:arr,
                    modalShowSet: true,
                    id:item.id
                })
            })



        }
    }
    fields = () => {
        return [{
            label: '角色名',
            type: 'input',
            name: 'name',
            options: {
                rules: [{
                    required: true,
                    message: '请输入用户名!',
                }]
            }
        },{
            label: '描述',
            type: 'input',
            name: 'description',
            options: {
                rules: [{
                    required: true,
                    message: '请输入内容!',
                }]
            }
        }]
    }

    fieldsEdit = () => {
        const item = this.state.item;
        return [{
            name: 'id',
            options:{
                initialValue: item.id,
            }
        },{
            label: '角色名',
            type: 'input',
            name: 'name',
            items: item.name,
            options: {
                initialValue: item.name,
                rules: [{
                    required: true,
                    message: '请输入用户名!',
                }]
            }
        },{
            label: '描述',
            type: 'input',
            name: 'description',
            items: item.description,
            options: {
                initialValue: item.description,
                rules: [{
                    required: true,
                    message: '请输入内容!',
                }]
            }
        }]
    }

    render() {
        return (
            <div id="wrap">

                <div className="tableBox">
                    <Button onClick={this.add} className="addButton">添加</Button>
                    <div style={{ paddingTop: 43 }}>
                        <Table
                            onCtrlClick={ this.tableAction }
                            total={this.state.total}
                            pageSize={this.state.pageSize}
                            current={this.state.current}
                            onChange= {this.changePage}
                            pagination={ true }
                            header={ this.tableHeader() }
                            data={ this.state.tData }
                            loading={ this.state.loading }
                            action={row => [{
                                key: 'edit',
                                name: '修改',
                                color: 'blue',
                                icon: 'edit',
                            }, {
                                key: 'delete',
                                name: '删除',
                                color: 'red',
                                icon: 'delete'
                            },{
                                    key: 'set',
                                    name: '分配',
                                    color: 'blue',
                                    icon: 'setting'
                                }]}
                            scroll={{y: 500 }}
                        />
                    </div>
                </div>
                <FormModal
                    modalKey="add"
                    visible={this.state.modalShow}
                    title="添加角色"
                    fields={this.fields()}
                    onOk={this.onOk}
                    onCancel={this.onCancel}
                    okText="保存"
                />
                <FormModal
                    modalKey="Edit"
                    visible={this.state.modalShowEdit}
                    title="修改角色"
                    fields={this.fieldsEdit()}
                    onOk={this.onOkEdit}
                    onCancel={this.onCancelEdit}
                    okText="保存"
                />
                <ModelTreeSelect
                       modalKey="set"
                       defaultArr={this.state.defaultArr}
                       data={this.state.menuDate}
                       visible={this.state.modalShowSet}
                       title="修改权限"
                       onOk={this.onOkSet}
                       getId ={this.getId}
                       onCancel={this.onCancelSet}
                       okText="保存"
                />


            </div>
        )
    }
}